package br.usp.trabalho.sd.master;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import br.usp.trabalho.sd.FileInfo;


public class FilesManager
{
    private static final String DIR_NAME = "info";

    private File mFilesDir;


    public FilesManager()
    {
        mFilesDir = new File(DIR_NAME);

        if (!mFilesDir.exists())
        {
            mFilesDir.mkdir();
        }
    }

    public synchronized FileInfo loadFile(String fileName) throws IOException
    {
        File file = new File(mFilesDir, fileName);
        ObjectInputStream reader = new ObjectInputStream(new FileInputStream(file));

        try
        {
            return (FileInfo) reader.readObject();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            reader.close();
        }

        return null;
    }


    public synchronized boolean saveFile(FileInfo info) throws IOException
    {
        if (info.isLocked()) return false;

        File file = new File(mFilesDir, info.getFileName());
        if (!file.exists()) file.createNewFile();

        ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream(file));
        try
        {
            writer.writeObject(info);
            return true;
        }
        finally
        {
            writer.close();
        }
    }
}
